package com.zhuhjay.framework.task;

import cn.hutool.core.io.FileUtil;
import com.zhuhjay.common.base.config.SystemConfig;
import com.zhuhjay.service.system.model.entity.SystemFile;
import com.zhuhjay.service.system.service.SystemFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 清理系统定时任务
 * @author ZhuHJay
 * @date 2023/6/5 15:57
 */
@Slf4j
@Component
@EnableScheduling
public class CleanSystemTask {

    @Resource
    private SystemFileService systemFileService;

    @Resource
    private SystemConfig systemConfig;

    @Scheduled(cron = "0 0 3 1/2 * ?")
    public void task() {
        // 数据库中存在的文件
        Set<String> dbFiles = systemFileService.lambdaQuery()
                .select(SystemFile::getIdentifier).list()
                .stream().map(SystemFile::getIdentifier).collect(Collectors.toSet());

        // 获取系统磁盘中的文件
        String path = systemConfig.getFileSystemPath();
        Set<String> diskFiles = FileUtil.loopFiles(path)
                .stream().map(FileUtil::getName).collect(Collectors.toSet());

        // 筛出数据库中不存在的文件
        diskFiles.removeAll(dbFiles);

        // 开始进行清理并记录日志
        StringBuilder sb = new StringBuilder();
        StopWatch stopWatch = new StopWatch();
        sb.append("\n===> 共发现 ").append(diskFiles.size()).append(" 个文件需要从磁盘中删除 <===\n");
        sb.append("--> \t\t删除任务开始\t\t <--\n");
        stopWatch.start();
        // 删除磁盘中不存在的文件
        diskFiles.forEach(name -> {
            String filePath = path + "/" + name;
            FileUtil.del(filePath);
            sb.append("删除文件 -> ").append(filePath).append("\n");
        });
        stopWatch.stop();
        sb.append("--> \t\t删除任务结束\t\t <--\n");
        sb.append("===> 共耗时: \t").append(stopWatch.getTotalTimeMillis()).append(" ms <===");

        log.info(sb.toString());
    }

}
